package com.longrise.android.byjk.plugins.course.coursedetail;

import android.content.Intent;
import android.os.Bundle;

import com.google.gson.Gson;
import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.LEAP.Base.Util.DateUtil;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.model.CourseTrainDirBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.certificate.CertActivity;
import com.longrise.android.byjk.plugins.course.coursedetail.courseevaluate.ScoreActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.byjk.plugins.course.pay.PaymentActivity;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by godliness on 2017/7/19.
 * 课程详情
 */

public class CoursePresenter extends CourseDetailContract.Presenter {

    private static final String TAG = "CoursePresenter";

    public static final int RESULT_UPDATE_CWID = 101;
    private CourseTrainDirBean mCourseTrainDirBean;

    private final int PARSE_BUY = 0;
    private final int PARSE_DELAY = 1;

    private boolean mFinished;

    public CourseTrainDirBean.Result mResult;
    private String mCourseID;

    @Override
    protected void init() {

    }


    @Override
    public void initData(String courseId) {
        this.mCourseID = courseId;
        toGetCourseinfo();

    }

    @Override
    public void refreshData() {
        toGetCourseinfo();
    }

    /**
     * 点击了课后练习题
     */
    @Override
    public void clickKhlxt() {
        if (mResult == null) {
            return;
        }
        boolean videopass = mResult.traindirstruct.dirinfo.get(0).nextnodeinfo.get(0).videopass;//视频是否播放完成
        if (videopass) { //视频看完了就可以做课后练习题
            mView.jumpToExercises();
        } else {
            mView.showToast("请先看完课程，再进行课后测试。");
        }
    }

    /**
     * 获取课程的信息
     */
    public void toGetCourseinfo() {
        EntityBean coursEntityBean = new EntityBean();
        coursEntityBean.set("cardno", UserInfor.getInstance().getUsersfzh());
        coursEntityBean.set("courseid", mCourseID);
        EntityBean argBean = new EntityBean();
        argBean.set("bean", coursEntityBean);
        LoadDataManager.getInstance()
                .callService(null, UrlConstants.BaseUrl, "bbt_course_sTrainResDirStructBean",
                        argBean, new LoadDataManager.OnRequestCallListener() {
                            @Override
                            public void onSuccess(String key, String service, Object result) {
                                if (!(result instanceof EntityBean)) {
                                    mView.showToast("数据结构异常");
                                    return;
                                }
                                try {
                                    EntityBean resultBean = (EntityBean) result;
                                    if (resultBean.getInt("resultstate") != 1) {
                                        String desc = resultBean.getString("resultdesc");
                                        mView.showToast(desc);
                                    } else {
                                        String serialize = JSONSerializer.getInstance().Serialize(resultBean);
                                        parseCourse(serialize);
                                        mView.dismissDefaultView();
                                    }
                                } catch (Exception e) {
                                    mView.showToast("数据解析异常...");
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                                mView.onError(mContext.getString(R.string.networkerr));
                            }

                            @Override
                            public void onFinished(String key, String service) {
                                mView.dismissLoadingDialog();
                            }
                        });
    }

    /**
     * 解析课程
     */
    private void parseCourse(String value) {
        Gson gson = new Gson();
        mCourseTrainDirBean = gson.fromJson(value, CourseTrainDirBean.class);
        mResult = mCourseTrainDirBean.result;
        mView.showMsg(mResult);


        setCourseInfor();
    }


    public void setFinished() {
        mFinished = true;
    }

    public void setCourseInfor() {
        dispatchCourseInfor();
        setCommentState();
    }

    private void setCommentState() {
        boolean isVisiable = mResult.traindirstruct.ispass ? true : mResult.issinguptrain && (mResult.isablestudy || mResult.isabledelaycourse);
        mView.setCommentVisiableState(isVisiable);
    }

    private void dispatchCourseInfor() {
        if (mResult == null || mResult.traindirstruct == null) {
            return;
        }
        //课程图片
        mView.loadCoursePic(mResult.realpic);
        //培训证证书
        dispatchCertInfor();
        //过期时间
        setExpiretime();
        //如果课件通过状态保留之前学习记录
        if (mResult.traindirstruct.ispass) {
            mView.setBuyInfor(false, "", false, false, "");
            return;
        }
        //开通信息
        dispatchBuyifor();
    }

    /**
     * 过期时间
     */
    private void setExpiretime() {
        String date = "";
        try {
            date = DateUtil.FormatDate(mResult.expiretime, DateUtil.dateFormat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mView.setExpiretime(date);
    }


    /**
     * isablestudy==false时，toast课程状态
     */
    public void dispatchStudyMsg() {
        if (mResult.isclose) {
            mView.showToast("该课程已下架");
            return;
        }
        boolean mIsablesignup = mResult.isablesignup;  //是否能够报名
        boolean isabledelaycourse = mResult.isabledelaycourse;  //是否能够延期
        if (!mIsablesignup && !isabledelaycourse) {
            mView.showToast("该课程已关闭");
            return;
        }
        boolean issinguptrain = mResult.issinguptrain;  //是否开通过
        if (!issinguptrain) {
            mView.showToast(mResult.isfree ? "请先开通该课程" : "请先购买该课程");
            return;
        }
        //最新版本取消，延期功能，仅提示过期
        mView.showToast("该课程已过期");
    }


    /**
     * 该部分逻辑  ！！！谨慎修改！！！，请用return处理
     * 培训证书，培训记录表显示状态
     */
    private void dispatchCertInfor() {
        int studyState = mResult.studystate;
        if (studyState == 2) {
            //如果待学习状态，强制不显示培训证书等，有一种情况: 列表页状态为“待学习”，实际已经有课件完成。
            mView.setCertInfor(false, false);
            return;
        }
        boolean isPass = mResult.traindirstruct.ispass;
        int grouptype = mResult.grouptype;
        int courseTotalFinishCWCount = mResult.traindirstruct.coursetotalfinishcwcount;
        boolean isAbleToPrintCer = mResult.isabletoprintcer;
        int videoPassCount = mResult.traindirstruct.videopasscount;
        if (isPass && grouptype != 0 && courseTotalFinishCWCount >= 1) {
            if (!isAbleToPrintCer) {
                //天津问题，只显示培训记录表
                mView.setCertInfor(false, true);
            } else {
                //显示培训证书与培训记录表
                mView.setCertInfor(true, true);
            }
            return;
        }
        if (courseTotalFinishCWCount >= 1 && videoPassCount >= 1) {
            //仅显示培训记录表
            mView.setCertInfor(false, true);
            return;
        }
        //不显示培训记录表与培训证书
        mView.setCertInfor(false, false);
    }

    /**
     * 该部分逻辑 ！！！谨慎修改！！！  注：请用return处理
     * 购买，开通，延期等相关逻辑
     * 1、首先判断是否可以学习，
     * 2、依次判断是否已下架，已关闭
     * 3、然后判断是否开通过
     * 4、最后判断是否可以延期  最新迭代该功能已取消
     */
    private void dispatchBuyifor() {
        boolean isablestudy = mResult.isablestudy;  //是否能够学习
        if (isablestudy) {
            //可以学习，显示立即学习按钮
            mView.setBuyInfor(false, "", false, false, "");
            return;
        }
        boolean isColse = mResult.isclose;
        if (isColse) {
            //已下架
            mView.setBuyInfor(false, "", false, true, "已下架");
            return;
        }
        boolean mIsablesignup = mResult.isablesignup;  //是否能够报名
        boolean isabledelaycourse = mResult.isabledelaycourse;  //是否能够延期
        boolean ispass = mResult.traindirstruct.ispass;
        if (!mIsablesignup && !isabledelaycourse) {
            if (!ispass) {
                //已关闭状态
                mView.setBuyInfor(false, "", false, true, "已关闭");
            } else {
                //考核通过，保留学习记录，隐藏关于购买/开通/下架/过期/关闭等相关按钮
                mView.setBuyInfor(false, "", false, false, "");
            }
            return;
        }
        boolean issinguptrain = mResult.issinguptrain;  //是否开通过
        if (!issinguptrain) {
            //立即开通、立即购买
            boolean isFree = mResult.isfree;
            mView.setBuyInfor(true, isFree ? "立即开通" : "立即购买", false, false, "");
            return;
        }
        //以下为：已经开通过issinguptrain==true，但不可以学习isablestudy==false，判断是否可以延期的处理逻辑
        if (!isabledelaycourse) {
            if (!ispass) {
                //不能延期  重新开通、重新购买
                boolean isFree = mResult.isfree;
                mView.setBuyInfor(true, isFree ? "重新开通" : "重新购买", false, false, "");
            } else {
                //隐藏所有按钮
                mView.setBuyInfor(false, "", false, false, "");
            }
            return;
        }
        //可以延期
        if (isabledelaycourse) {
            if (!ispass) {
                //重新开通、重新购买    立即延期
                boolean isFree = mResult.isfree;
                //V1.3.7去除延期功能，故延期功能直接为false
                mView.setBuyInfor(true, isFree ? "重新开通" : "重新购买", false, false, "");
            } else {
                //隐藏所有按钮
                mView.setBuyInfor(false, "", false, false, "");
            }
        }
    }

    /**
     * to评分页
     */
    public void toScoreActivity(CourseDetailActivity2 act) {
        ScoreActivity.toPushActivity(act,mView.getCourseId());
    }


    /**
     * 培训证书
     */
    public void toCertActivity() {
        if (mResult == null) {
            return;
        }
        mContext.startActivity(getCertIntent(CertActivity.CertType.TYPE_CERT));
    }

    private Intent getCertIntent(int type) {
        VideoParams vp = new VideoParams();
        vp.mCourseId = mResult.courseid;
        vp.mStudentNo = mResult.studentno;
        vp.mTrainsiqnupid = mResult.trainsignupid;
        vp.mFinish = mResult.traindirstruct.ispass;  //这里为课程是否通过
        vp.mType = type;
        Intent paramsIntent = new Intent(mContext, CertActivity.class);
        paramsIntent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, vp);
        return paramsIntent;
    }

    /**
     * 培训记录表
     */
    public void toRecordActivity() {
        if (mResult == null) {
            return;
        }
        mContext.startActivity(getCertIntent(CertActivity.CertType.TYPE_TABLE));
    }

    /**
     * 购买
     * 非免费课程去 课程支付页面统一开通 20171127
     */
    public void toBuyCourse() {
        if(mResult !=null && !mResult.isfree){  //不是免费的 就直接去购买 现在不需要
            mView.toConfirmOrder();
        }else{
            toRequest();
        }
    }

    private void toRequest() {
        mView.showLoadingDialog();
        mView.setEnable(false);
        EntityBean bean = new EntityBean();
        bean.set("courseid", mView.getCourseId());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        final EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_course_openTrainFroBBTapp", reqBean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (mFinished) {
                            return;
                        }
                        if (!(reqBean instanceof EntityBean)) {
                            //数据结构异常
                            mView.showToast("数据结构异常");
                            return;
                        }
                        EntityBean resultBean = (EntityBean) result;
                        int state = resultBean.getInt("resultstate");
                        if (state != 1) {
                            mView.showToast(resultBean.getString("resultdesc"));
                            return;
                        }
                        EntityBean resultStr = resultBean.getBean("result");
                        parseBuy(resultStr);
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        mView.showToast(mContext.getString(R.string.networkerr));
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        mView.dismissLoadingDialog();
                        mView.setEnable(true);
                    }
                });
    }

    /**
     * 解析购买或开通
     */
    private void parseBuy(EntityBean result) {
        boolean isneedpay = result.getBoolean("isneedpay");
        PrintLog.e(TAG, "isneedpay: " + isneedpay);
        if (isneedpay) {
            //EntityBean signupBean = result.getBean("signupBean");
            mView.toConfirmOrder();
        } else {
            mView.showToast("成功开通该课程");
            //必须要重新请求该数据，否则获取不到学习记录
            refreshData();

            //我的课程页面刷新数据还包括我的界面的刷新
            CourseDetailEvent event = new CourseDetailEvent();
            event.setCourseBuyStatus(true);
            EventBus.getDefault().post(event);
        }
    }



    /**
     * 解析延期  该功能已不存在 V1.3.7删除
     */
    private void parseDelay(EntityBean result) {
        boolean isdelaysucess = result.getBoolean("isdelaysucess");
        if (isdelaysucess) {
            String expirationdate = result.getString("expirationdate"); //延期时间
            mView.showDelaySuccessDialog();

        } else {
            //不应该返回false的
        }
    }

    /**
     * 延期 该功能已不存在 V1.3.7删除
     */
    public void toDelayCourse() {
        //最新已没有延期功能
//        toRequest(PARSE_DELAY);
    }

}
